package com.bird.extension.reflect;

import lombok.var;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @Author: sijunqiang
 * @Date: 2020/4/5 14:00
 * @Description: use reflect technology to get object inner all method
 */
public class MethodCollector {


    public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {

        // 1: begin get Big target Class object
        Class reflectTargetClass = Class.forName("com.bird.extension.reflect.ReflectTarget");

        // 2: get all public method contain( parent and object )
        System.out.println("**********************get all public method contain( parent and object ) *******************");
        Method[] methodArray = reflectTargetClass.getMethods();
        for (Method method : methodArray) {
            System.out.println(method);
        }

        //3： get the class all method
        System.out.println("**************** get the class all method************************");
        Method[] declaredMethods = reflectTargetClass.getDeclaredMethods();
        for (Method method : declaredMethods) {
            System.out.println(method);
        }

        //4: get single public method and invoke the method
        System.out.println("***************get single public method and invoke the method ******************");
        Method declaredMethod = reflectTargetClass.getDeclaredMethod("show1", String.class);
        System.out.println(declaredMethod);
        ReflectTarget reflectTarget = (ReflectTarget) reflectTargetClass.getConstructor().newInstance();
        declaredMethod.invoke(reflectTarget, "hello this is  my first use reflect get public method ");

        //get single private method
        System.out.println("****************get single private method ****************************");
        Method privateMethod = reflectTargetClass.getDeclaredMethod("show4", int.class);
        System.out.println(privateMethod);
        privateMethod.setAccessible(true);
        String result = (String) privateMethod.invoke(reflectTarget, 20);
        System.out.println("private method return result：" + result);
    }
}
